package cmd

import (
	"bufio"
	"fmt"
	l4g "github.com/alecthomas/log4go"
	"github.com/spf13/cobra"
	"os"
	"os/exec"
)

func ExecuteCommand(name string, subname string, args ...string) (string, error) {
	args = append([]string{subname}, args...)
	return ExecuteCommandSimple(name,args...)
}

func ExecuteCommandSimple(name string, args ...string)(string, error) {
	cmd := exec.Command(name, args...)
	bytes, err := cmd.CombinedOutput()
	return string(bytes), err
}

func ExecuteCommandOut(name string, subname string, args ...string)  error {
	args = append([]string{subname}, args...)
	cmd := exec.Command(name, args...)
	stdoutPipe, err := cmd.StdoutPipe()
	if err != nil {
		return  err
	}
	defer stdoutPipe.Close()
	go func() {
		scanner := bufio.NewScanner(stdoutPipe)
		for scanner.Scan() {
			l4g.Info(string(scanner.Bytes()))
		}
	}()
	if err = cmd.Run(); err != nil {
		return err
	}
	return nil
}

func Error(cmd *cobra.Command, args []string, err error) {
	fmt.Fprintf(os.Stderr, "execute %s args:%v error:%v\n", cmd.Name(), args, err)
	os.Exit(1)
}